import { defineStore } from 'pinia'
import { getUserMenusByRoleId, loginRequest } from '@/service/system/login/login'
import type { LoginAccount } from '../../types'
import { localCache } from '@/util/cache.ts'
import router from '@/router'
import { Token } from '@/global/constants'
import { ElMessage } from 'element-plus'
import { type RouteRecordRaw} from 'vue-router'
import { ref } from 'vue'
import { mapMenusToRoutes } from '@/util/map-menus.ts'

// 制定status 的类型
interface ILoginState {
  token: string
  userinfo: object
  msg: string
  code: string
  userMenus: RouteRecordRaw[]
}

//  定义菜单 类型
interface Menu {
  component_name: string;
  icon: string;
  id: string;
  level: number;
  name: string;
  order: number;
  parent_id: string;
  path: string;
  sub_menus: Menu[];
}

const useLoginStore = defineStore('login', {
  state: (): ILoginState =>  ({
    //
    token: localCache.getCache(Token) ?? '',
    msg: '',
    code: '',
    userinfo: localCache.getCache("userinfo") ?? {},
    userMenus: localCache.getCache("userMenus") ?? [],
  }),
  actions: {
    async loginAccountAction(account: LoginAccount) {
      // 向服务器发送网络请求
      //console.log(account)
      const loginResult = await loginRequest(account)

      // ===========提示登录成功或失败============
      this.code = loginResult.data.code
      this.msg = loginResult.data.msg
      if (this.code != "200") {
        ElMessage.error(this.msg)
      } else {
        ElMessage.success(this.msg)
      }
      // ===========提示登录成功或失败============
      // 保存token到本地
      this.token = loginResult.data.token
      // 进行本地的缓存
      localCache.setCache(Token, this.token)

      // 获取用户的详细信息（主要是角色和权限）
      this.userinfo = {
        userid: loginResult.data.result.user_id,
        username: loginResult.data.result.username,
        realname: loginResult.data.result.realname,
        departid: loginResult.data.result.depart_id,
        departname: loginResult.data.result.depart_name,
        roleid: loginResult.data.result.role_id,
        rolename: loginResult.data.result.role_name,
        isadmin: Boolean(loginResult.data.result.is_admin),
        menus: loginResult.data.result.menu_info,
      }
      localCache.setCache("userinfo", this.userinfo)

      const userMenus = ref<Menu[]>([])
      const data =  await  getUserMenusByRoleId({ id: loginResult.data.result.role_id})
      userMenus.value = data.data.result
      // 将菜单添加到缓存
      localCache.setCache('userMenus', userMenus.value)
      // 跳转到主页
      if (this.code != "200") {
        await router.push('/home')
      }else {
        await router.push('/login')
      }
    },
    loadLocalCacheAction(){
      // 用户刷新默认加载数据
      const token = localCache.getCache(Token)
      const userinfo = localCache.getCache("userinfo")
      const userMenus = localCache.getCache("userMenus")
      if (token && userinfo && userMenus) {
        this.token = token
        this.userinfo = userinfo
        this.userMenus = userMenus

        //  添加动态路由
        const routes =  mapMenusToRoutes(this.userMenus)
        routes.forEach((route) => router.addRoute("home",route))
      }
    }
  }
})

export default useLoginStore
